
package com.ojoin.trade.supplyloan_core.web.service.impl;

import java.math.BigDecimal;
import java.util.Arrays;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.ojoin.trade.supplyloan_core.web.domain.*;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import com.ojoin.trade.common.constdef.IConstDef;
import com.ojoin.trade.common.exception.BusinessException;
import com.ojoin.trade.common.utils.BeanMapUtils;
import com.ojoin.trade.common.utils.CommonUtils;
import com.ojoin.trade.common.utils.Config;
import com.ojoin.trade.common.utils.LogUtils;
import com.ojoin.trade.common.utils.TimeUtils;
import com.ojoin.trade.common.utils.paynow.ThreeDESEncryptProvider;
import com.ojoin.trade.common.web.dao.BaseDao;
import com.ojoin.trade.common.web.service.TbUploadFileService;
import com.ojoin.trade.common.web.service.impl.BaseServiceImpl;
import com.ojoin.trade.common_core.web.service.impl.DataVersionValidationService;
import com.ojoin.trade.supplyloan_core.constdef.ISLConstDef;
import com.ojoin.trade.supplyloan_core.web.dao.TbSlPlatformUserDao;
import com.ojoin.trade.supplyloan_core.web.service.TbSlCreditInfoService;
import com.ojoin.trade.supplyloan_core.web.service.TbSlLoanApplicationService;
import com.ojoin.trade.supplyloan_core.web.service.TbSlLoanCreditService;
import com.ojoin.trade.supplyloan_core.web.service.TbSlLoanStatTotalService;
import com.ojoin.trade.supplyloan_core.web.service.TbSlPlatformUserService;

/**
 * Created with IntelliJ IDEA.
 * User: Administrator
 * Date: 15-10-28
 * Time: 下午2:35
 * To change this template use File | Settings | File Templates.
 */
@Service
public class TbSlPlatformUserServiceImpl extends BaseServiceImpl<TbSlPlatformUser> implements TbSlPlatformUserService {
	@Autowired
	private DataVersionValidationService validateservice;
	
	@Autowired
	private TbSlLoanStatTotalService totalService;
	
	@Autowired
	private TbSlLoanApplicationService slloanservice;
	
    @Autowired
    private TbUploadFileService uploadFileService;
	
    @Autowired
	private TbSlCreditInfoService creditInfoService;
    
	@Autowired
    private TbSlPlatformUserDao dao;

    @Autowired
    private TbSlLoanCreditService creditService;

    @Override
    protected BaseDao<TbSlPlatformUser> getBaseDao() {
        return dao;
    }

    @Override
    public void insertTbSlPlatformUser(TbSlPlatformUser uservo) throws BusinessException {
        ((TbSlPlatformUserDao)this.getBaseDao()).insert(uservo);
    }
    
    
    public int deleteByJoinId(int joinId) throws BusinessException{
    	TbSlLoanApplication applyvo = slloanservice.queryById(joinId);
    	if (applyvo.getLoanstatus() != null && applyvo.getLoanstatus() == ISLConstDef.SLLOANSTATUS_MATERIALPASSED)
    		throw new BusinessException("用户已成功申请供应链贷业务，不可删除电商平台信息，请联系管理员.");
    	
    	return ((TbSlPlatformUserDao)this.getBaseDao()).deleteByJoinId(joinId);
    }

    @Override
    public void deleteByJoinAndId(int joinid, int id) throws BusinessException {
    	TbSlLoanApplication applyvo = slloanservice.queryTbSlApplicationByJoinId(joinid);
    	if (applyvo!= null && applyvo.getLoanstatus() == ISLConstDef.SLLOANSTATUS_MATERIALPASSED)
    		throw new BusinessException("用户已成功申请供应链贷业务，不可删除电商平台信息，请联系管理员.");
    	
        ((TbSlPlatformUserDao)this.getBaseDao()).deleteByJoinandId(joinid,id);
    }


    /**
     * 初始添加平台
     */
    @Override
    public void insertAndDeleteSlPlatformUser(List<TbSlPlatformUser> list) throws BusinessException {
        dao.deleteByJoinId(list.get(0).getIdOfTbMerchantUser());
        for (TbSlPlatformUser entity : list) {
            dao.insert(entity);
        }
    }
     
    @Override
    public void updateTbSlPlatFormUser(Map<String, Object> map) throws BusinessException {
        ((TbSlPlatformUserDao)this.getBaseDao()).updateTbSlPlatFormUser(map);
    }

    @Override
    public List<TbSlPlatformUser> queryTbSlPlatformUser(String platformName) throws BusinessException {
        return  ((TbSlPlatformUserDao)this.getBaseDao()).queryTbSlPlatFormByPlatformType(platformName);
    }

    @Override
    public List<TbSlPlatformUser> queryTbSlPlatformUserByJoinid(String platformName, int joinid) throws BusinessException {
        return   ((TbSlPlatformUserDao)this.getBaseDao()).queryTbSlPlatFormByJoinidandName(platformName, joinid);
    }

	@Override
	public List<TbSlPlatformUser> queryVagueByName(String platformName)
			throws BusinessException {
		 return  ((TbSlPlatformUserDao)this.getBaseDao()).queryVagueByName(platformName);
	}

 
	@Override
    public List<TbSlPlatformUser> selectPlatformUserListByJoinID(int joinid) throws BusinessException {
        return ((TbSlPlatformUserDao)this.getBaseDao()).selectPlatformUserListByJoinID(joinid);
    }

	@Override
    public List<TbSlPlatformUserVO> selectAllPlatformUserListByJoinID(int joinid, Pageable page) throws BusinessException {
		List<TbSlPlatformUserVO>  ret=((TbSlPlatformUserDao)this.getBaseDao()).selectAllPlatformUserListByJoinID(joinid, page);
        return ret;
    }

    /**保理端的暂停平台
     ** @param id
     * @param enableflag
     * @return
     * @throws BusinessException
     */
	@Override
	public int updatePlatformUserEnableflagById(int id, String enableflag)
			throws BusinessException {
        List<TbSlLoanCreditLog> list= creditService.queryNotPayBackByPlatform(id);
        if(!CommonUtils.isEmpty(list)){
            throw  new BusinessException("该平台还有欠款，不能暂停");
        }
          return ((TbSlPlatformUserDao)this.getBaseDao()).updatePlatformUserEnableflagById(id, enableflag);
	}

    /**商户端的暂停平台
     *@param id
     * @param joinuserid
     * @param enableflag
     * @return
     * @throws BusinessException
     */
	@Override
	public int updatePlatformUserEnableflagByPIdAndJId(int id, int joinuserid, String enableflag)
			throws BusinessException {
        List<TbSlLoanCreditLog> list= creditService.queryNotPayBackByPlatform(id);
        if(!CommonUtils.isEmpty(list)){
            throw  new BusinessException("该平台还有欠款，不能暂停");
        }
        if(enableflag.equals(ISLConstDef.PLATFORM_STATUS_PAUSED)){
            creditService.cancelForPausedPlatform(id);
        }
		return ((TbSlPlatformUserDao)this.getBaseDao()).updatePlatformUserEnableflagByPIdAndJId(id, joinuserid, enableflag);
	}
	
	@Override
	public int updatePlatformUserEnableflagByJoinuserId(int joinuserid,
			String enableflag) throws BusinessException {
		return ((TbSlPlatformUserDao)this.getBaseDao()).updatePlatformUserEnableflagByJoinuserId(joinuserid, enableflag);
	}
	
	

	@Override
	public int isExistPausedPlatformUserByJoinuserId(int joinuserid)
			throws BusinessException {
		return ((TbSlPlatformUserDao)this.getBaseDao()).isExistPausedPlatformUserByJoinuserId(joinuserid);
	}

	@Override
	public List<TbSlPlatformUserVO> selectPlatformUserListByNameAndFlag(
			String joinuserid, String platform_name, String enable_flag)
			throws BusinessException {
		return ((TbSlPlatformUserDao)this.getBaseDao()).selectPlatformUserListByNameAndFlag(joinuserid, platform_name, enable_flag);
		
	}

	@Override
	public List<TbSlPlatformUserWithdrawVO> selectPlatformUserWithdrawListByJoinuserId(
			int joinuserid) throws BusinessException {
		String statDate = TimeUtils.getCurDate();
		List<TbSlLoanStatTotalVo> totalList = totalService.queryByPlatformAndMerchantUserIDAndDate(null, joinuserid + "", statDate);
		HashMap<Integer, TbSlLoanStatTotalVo> map = new HashMap<Integer, TbSlLoanStatTotalVo>();
		if (totalList != null && totalList.size() > 0) {
			for(TbSlLoanStatTotalVo vo : totalList) {
				map.put(vo.getIdOfPlatformUser(), vo);
			}
		}

		List<TbSlPlatformUserWithdrawVO> platformUserList = ((TbSlPlatformUserDao)this.getBaseDao()).selectPlatformUserWithdrawListByJoinuserId(joinuserid);
		if (platformUserList != null && platformUserList.size() > 0) {
			for(TbSlPlatformUserWithdrawVO vo : platformUserList) {
				TbSlLoanStatTotalVo totalvo = map.get(vo.getId());
				if (totalvo == null)
					continue;
				
				vo.setTodayPaySettleorder(totalvo.getTotalPaySettleorder());
				vo.setTodayUnenterinRefundorder(totalvo.getTotalUnenterinRefundorder());
				vo.setTodayUnpaySettleorder(totalvo.getTotalUnpaySettleorder());
				vo.setTodayUnsettleInstoreorder(totalvo.getTotalUnsettleInstoreorder());
				vo.setTotalAmount(totalvo.getTotalAll());
			}
		}
		
		return platformUserList;
	}

	@Override
	public void updatePlatformUserCredit(TbSlPlatformUser vo)
			throws BusinessException {
		LogUtils.getSlloanLog().info(
				"供应链贷款为电商平台用户授信. " + BeanMapUtils.getString(vo));
		validateservice.validateVO(vo.getId(), vo.getTableName(), vo.getRowUpdateTime());
		
		vo.setEnableFlag(ISLConstDef.PLATFORM_STATUS_ENABLED);
		
		((TbSlPlatformUserDao)this.getBaseDao()).slPlatformUserCredit(vo);
		
		//更新上传文件状态为已提交
		uploadFileService.updateStatusById(CommonUtils.getInt(vo.getCreditCertificate()), IConstDef.UPLOADSTATUS_COMMITED);
	}

	@Override
	public void updatePlatformUserCredit(TbSlPlatformUserVO vo)
			throws BusinessException {
		LogUtils.getSlloanLog().info(
				"供应链贷款为电商平台用户授信. " + BeanMapUtils.getString(vo));
		validateservice.validateVO(vo.getId(), vo.getTableName(), vo.getRowUpdateTime());
		
		vo.setEnableFlag(ISLConstDef.PLATFORM_STATUS_ENABLED);
		
		((TbSlPlatformUserDao)this.getBaseDao()).slPlatformUserCredit(vo);
		
		//更新上传文件状态为已提交
		uploadFileService.updateStatusById(CommonUtils.getInt(vo.getCreditCertificate()), IConstDef.UPLOADSTATUS_COMMITED);
	}
	
	@Override
	public int selectUncreditPlatformUserByJoinuserId(int joinuserid)
			throws BusinessException {
		return ((TbSlPlatformUserDao) this.getBaseDao())
				.selectUncreditPlatformUserByJoinuserId(joinuserid);
	}

	@Override
	public List<TbSlPlatformUserVO> selectPlatformUserListByNameAndFlag(
			String joinuserid, String platform_name, String enable_flag,Pageable page)
			throws BusinessException {
		return ((TbSlPlatformUserDao)this.getBaseDao()).selectPlatformUserListByNameAndFlag(joinuserid, platform_name, enable_flag,page);
		
	}

	@Override
	public void updateTbSlPlatFormUserPwd(int joinuserid, int platformuserid, String oldpwd, String newpwd) throws BusinessException {
		if (CommonUtils.isEmpty(oldpwd)) {
			throw new BusinessException("旧密码不可为空，请检查.");
		}
		if (CommonUtils.isEmpty(newpwd)) {
			throw new BusinessException("新密码不可为空，请检查.");
		}
		TbSlPlatformUser platformUservo = this.queryById(platformuserid);
		platformUservo.decPassword();
		if (!CommonUtils.isEqual(oldpwd, platformUservo.getPassword())) {
			throw new BusinessException("旧密码不正确，请检查.");
		}
		
		//新密码加密
		String DSEKey = Config.getProperty("ipaynow.dsekey");//3DES需要的key
        String encryptPwd = ThreeDESEncryptProvider.encrypt(newpwd, DSEKey);
        
        //更新新密码
		((TbSlPlatformUserDao)this.getBaseDao()).updateTbSlPlatFormUserPwd(joinuserid, platformuserid, encryptPwd);
		
	}

    @Override
    public TbSlPlatformUser selectPlatformById(int id) throws BusinessException {
        return  getBaseDao().selectById(id);
    }

    @Override
	public void updateMerchantUserCreditCheckInfo(TbSlCreditInfo infovo)
			throws BusinessException {
    	
    	List<TbSlPlatformUser> platformUserList = this.selectPlatformUserListByJoinID(infovo.getIdOfTbMerchantUser());
    	if (platformUserList == null || platformUserList.size() == 0)
    		return;
    	
    	for(TbSlPlatformUser uservo : platformUserList) {
    		TbSlCreditInfo newinfovo = new TbSlCreditInfo();
    		newinfovo.setCreditDate(infovo.getCreditDate());
    		newinfovo.setCreditFile(infovo.getCreditFile());
    		newinfovo.setCreditNo(infovo.getCreditNo());
    		newinfovo.setIdOfTbMerchantUser(infovo.getIdOfTbMerchantUser());
    		newinfovo.setIdOfPlatform(uservo.getId());
    		
    		//新增该电商平台的征信记录
    		creditInfoService.insert(newinfovo);
    		
    		//更新平台信息的征信字段为征信记录主键
    		HashMap<String, Object> parammap = new HashMap<String, Object>();
    		parammap.put("id", uservo.getId());
    		parammap.put("creditcheckCertificate", newinfovo.getId());
    		this.updateTbSlPlatFormUser(parammap);
    	}
		
		//更新上传文件状态为已提交
		uploadFileService.updateStatusById(CommonUtils.getInt(infovo.getCreditFile()), IConstDef.UPLOADSTATUS_COMMITED);
	}
    
	@Override
	public void updatePlatformUserCreditCheckInfo(TbSlCreditInfo infovo)
			throws BusinessException {
		LogUtils.getSlloanLog().info(
				"供应链贷款为电商平台用户提交征信信息. " + BeanMapUtils.getString(infovo));
		validateservice.validateVO(infovo.getIdOfPlatform(), new TbSlPlatformUser().getTableName(), infovo.getRowUpdateTime());
		
		//删除并新增征信记录
		creditInfoService.deleteCreditInfo(infovo.getIdOfTbMerchantUser(), infovo.getIdOfPlatform());
		creditInfoService.insert(infovo);
		
		//更新平台信息的征信字段为征信记录主键
		HashMap<String, Object> parammap = new HashMap<String, Object>();
		parammap.put("id", infovo.getIdOfPlatform());
		parammap.put("creditcheckCertificate", infovo.getId());
		this.updateTbSlPlatFormUser(parammap);
		
		//更新上传文件状态为已提交
		uploadFileService.updateStatusById(CommonUtils.getInt(infovo.getCreditFile()), IConstDef.UPLOADSTATUS_COMMITED);
	}

	/**
	 * 对平台提现详情数据集合按availableCredit字段大小进行排序
	 */
	public List<TbSlPlatformUserWithdrawVO> sortPlatformUserWithdrawVOByAvailableCredit(List<TbSlPlatformUserWithdrawVO> withdrawList) {
		TbSlPlatformUserWithdrawVO[] withdrawvos = withdrawList.toArray(new TbSlPlatformUserWithdrawVO[0]);
		Arrays.sort(withdrawvos, new Comparator<TbSlPlatformUserWithdrawVO>() {

			@Override
			public int compare(TbSlPlatformUserWithdrawVO o1, TbSlPlatformUserWithdrawVO o2) {
				BigDecimal o1_rate_fee = new BigDecimal(o1.getRate()).add(new BigDecimal(o1.getFee()));
				BigDecimal o2_rate_fee = new BigDecimal(o2.getRate()).add(new BigDecimal(o2.getFee()));
				
				BigDecimal o1_available_credit = new BigDecimal(o1.getAvailableCredit());
				BigDecimal o2_available_credit = new BigDecimal(o2.getAvailableCredit());
				
				
				if (o1_rate_fee.compareTo(o2_rate_fee)  == 0) {
					return o2_available_credit.compareTo(o1_available_credit);
				} else {
					return o1_rate_fee.compareTo(o2_rate_fee);
				}
				
//				double o1_rate_fee = CommonUtils.getdouble(o1.getRate())+CommonUtils.getdouble(o1.getFee());
//				double o2_rate_fee = CommonUtils.getdouble(o2.getRate())+CommonUtils.getdouble(o2.getFee());
//				
//				if (o1_rate_fee < o2_rate_fee) {
//					return -1;
//				} else if (o1_rate_fee > o2_rate_fee) {
//					return 1;
//				} else if (Double.compare(o1_rate_fee,o2_rate_fee)==0) {
//					if(Double.compare(o1.getAvailableCredit(), o2.getAvailableCredit()) > 0)
//						return -1;
//					
//					if(Double.compare(o1.getAvailableCredit(), o2.getAvailableCredit()) < 0)
//						return 1;
//
//					return 0;
//				}
//				
//				return 0;
			}

		});
		
		return Arrays.asList(withdrawvos);
	}

	@Override
	public int updateMerchantUserCreditInfoByJoinuserId(int joinuserid,
			int creditinfoid) throws BusinessException {
		return ((TbSlPlatformUserDao) this.getBaseDao())
				.updateMerchantUserCreditInfoByJoinuserId(joinuserid, creditinfoid);
	}

	@Override
	public void updateApplyPlatformWithUpDownStreamContract(int joinid ,String fileId) throws BusinessException {
		TbSlPlatformUser quser=new TbSlPlatformUser();
		quser.setIdOfTbMerchantUser(joinid);
		List<TbSlPlatformUser> platformUserList = this.queryList(quser);
		for(TbSlPlatformUser pf:platformUserList){
			pf.setBusiContract(fileId);
		}
		this.updateInBatch(platformUserList);
	}

    @Override
    public List<TbPlatformExpireVo> queryTbPlatformExpire(int joinuserid) throws BusinessException {
        return ((TbSlPlatformUserDao) this.getBaseDao()).queryTbPlatformExpire(joinuserid);
    }

	@Override
	public List<TbSlPlatformUser> queryTbSlPlatformUserByJoinid(int joinid)
			throws BusinessException {
		return queryTbSlPlatformUserByJoinid(null, joinid);
	}


}

